﻿using System;
using System.Collections.Generic;
using Autofac;
using QQ2564874169.RelationalSql;

namespace TestConsole
{
    public class DbExecuteMonitorResolver : IDbExecuteMonitorResolver
    {
        private ILifetimeScope _scope;
        private List<ILifetimeScope> _disposes = new List<ILifetimeScope>();

        public DbExecuteMonitorResolver(ILifetimeScope scope)
        {
            _scope = scope;
        }

        public void Dispose()
        {
            _disposes.Reverse();
            foreach (var item in _disposes)
            {
                item.Dispose();
            }
            _disposes.Clear();
            _disposes = null;
        }

        public IDbExecuteMonitorResolver NewScope()
        {
            return new DbExecuteMonitorResolver(_scope.BeginLifetimeScope());
        }

        public object CreateBeforeInstance(Type serviceType, ISql sql)
        {
            _scope = _scope.BeginLifetimeScope(cb =>
            {
                cb.RegisterInstance(sql).ExternallyOwned().AsImplementedInterfaces().SingleInstance();
            });
            _disposes.Add(_scope);
            return _scope.Resolve(serviceType);
        }

        public object CreateAfterInstance(Type serviceType)
        {
            return _scope.Resolve(serviceType);
        }
    }
}
